package com.feng.vhr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.vhr.mapper.HrMapper;
import com.feng.vhr.pojo.Hr;
import com.feng.vhr.pojo.HrRole;
import com.feng.vhr.pojo.Role;
import com.feng.vhr.response.RHr;
import com.feng.vhr.service.IHrRoleService;
import com.feng.vhr.service.IHrService;
import com.feng.vhr.service.IRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author feng
 * @since 2022-05-09
 */
@Service
public class HrServiceImpl extends ServiceImpl<HrMapper, Hr> implements IHrService, UserDetailsService {
    @Resource
    private HrMapper hrMapper;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IHrRoleService hrRoleService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        RHr rHr = new RHr();
        QueryWrapper<Hr> wrapper = new QueryWrapper<>();
        wrapper.eq("username", s);
        Hr hr = hrMapper.selectOne(wrapper);
        if (hr == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        QueryWrapper<HrRole> hrRoleQueryWrapper = new QueryWrapper<>();
        hrRoleQueryWrapper.eq("hrid", hr.getId());
        List<HrRole> hrRoles = hrRoleService.list(hrRoleQueryWrapper);
        List<Role> roles = new ArrayList<>();
        roles = hrRoles.stream().map(item -> {
            Role role = roleService.getById(item.getRid());
            return role;
        }).collect(Collectors.toList());
        BeanUtils.copyProperties(hr, rHr);
        rHr.setRoles(roles);
        return rHr;
    }
}
